var generateMatrix = function (n) {
    let l = 0, r = n - 1, t = 0, b = n - 1;
    let res = new Array(n).fill(0).map(() => new Array(n).fill(0));
    let num = 1, end = n * n;
    while (num <= end) {
        for (let i = l; i <= r; i++) res[t][i] = num++; // left to right.
        t++;
        for (let i = t; i <= b; i++) res[i][r] = num++; // top to bottom.
        r--;
        for (let i = r; i >= l; i--) res[b][i] = num++; // right to left.
        b--;
        for (let i = b; i >= t; i--) res[i][l] = num++; // bottom to top.
        l++;
    }
    return res;
};

let res = generateMatrix(3);
console.log(res);